import React, {useState, useEffect, useImperativeHandle, forwardRef} from 'react';
import {Card, Row, Col, Pagination, Spin, Empty, Form} from 'antd';
import ProductSearchForm from './ProductSearchForm';
import ProductCard from './ProductCard';
import type {Product, ProductSearchParams} from './data';
import styles from './index.less';
import {pageProduct} from "@/pages/organization/product-manager/api";

interface ProductSelectProps {
  initialSearchParams?: Partial<ProductSearchParams>; // 自定义搜索参数
  showSearch?: boolean | { brand: boolean; category: boolean; returnTong: boolean; name: boolean }; // 是否显示搜索区域
  cardActions?: (product: Product) => React.ReactNode[]; // 自定义卡片操作按钮
  pageSize?: number; // 分页大小
  onChange?: (product: Product) => void; // 操作按钮点击回调
  onFetch?: (params: any) => Promise<{
    data: Product[];
    total: number;
  }>;
  customerId?: string;
  showInventory?: boolean;
}

export interface ProductSelectRef {
  reload: () => Promise<void>;
}

const ProductSelect = forwardRef<ProductSelectRef, ProductSelectProps>(
  (props, ref) => {
    const {
      initialSearchParams = {},
      showSearch = true,
      cardActions,
      pageSize = 12,
      onChange,
      onFetch,
      customerId,
      showInventory
    } = props;

    const [searchParams, setSearchParams] = useState<Partial<ProductSearchParams>>({
      ...initialSearchParams,
      pageSize,
      current: 1,
    });
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<{ data: Product[]; total: number }>();
    const [form] = Form.useForm();

    // API请求方法
    const fetchProducts = async (params: any) => {
      setLoading(true);
      try {
        if (onFetch) {
          const data = await onFetch({...params, customerId});
          setData(data);
        } else {
          const {data} = await pageProduct({...params, customerId});
          setData(data);
        }
      } finally {
        setLoading(false);
      }
    };

    useEffect(() => {
      form.resetFields();
      fetchProducts(searchParams);
    }, [searchParams]);

    const handleSearch = (values: Partial<ProductSearchParams>) => {
      setSearchParams({
        ...values,
        ...initialSearchParams,
        current: 1,
        pageSize,
      });
    };

    const handlePageChange = (current: number, size?: number) => {
      setSearchParams({
        ...searchParams,
        current,
        pageSize: size || pageSize,
      });
    };

    const reload = async () => {
      handleSearch({})
    };

    useImperativeHandle(ref, () => ({
      reload
    }), []);

    return (
      <div className={styles.productSelect}>
        {showSearch && (
          <Card className={styles.searchCard}>
            <ProductSearchForm
              form={form}
              initialValues={initialSearchParams}
              onSearch={handleSearch}
              showSearch={showSearch}
            />
          </Card>
        )}

        <Spin spinning={loading}>
          <div className={styles.productList}>
            {data?.data?.length ? (
              <Row gutter={[16, 16]}>
                {data.data.map((product) => (
                  <Col key={product.id} xs={12} sm={8} md={8} lg={8} xl={6}>
                    <ProductCard
                      product={product}
                      actions={cardActions?.(product)}
                      onProductClick={(product) => {
                        onChange?.(product);
                      }}
                      showInventory={showInventory}
                    />
                  </Col>
                ))}
              </Row>
            ) : (
              <Empty description="暂无商品数据"/>
            )}
          </div>

          <div className={styles.pagination}>
            <Pagination
              current={searchParams.current}
              pageSize={searchParams.pageSize}
              total={data?.total || 0}
              onChange={handlePageChange}
              pageSizeOptions={[12, 24, 36, 48]}
              showSizeChanger
              showQuickJumper
              showTotal={(total) => `共 ${total} 条`}
            />
          </div>
        </Spin>
      </div>
    );
  }
)

export default ProductSelect;
